# -*- coding: utf8 -*-

from django.utils.safestring import mark_safe

"""Metoda do wsadzania unicode do RTF - jesli umowy beda w docx, bedzie raczej zbedna"""
def rtf_repr(s):
    import re
    s = repr(s)
    s = s[2:-1]
    for i in re.findall('\u([0-9a-f]{4})', s):
        dec = int(i, 16)
        s = re.sub('\\\u%s' % i, '\u%s?' % dec, s) 
    return s

    
class Table:
    headers = []
    data = []
    renderers = []
    
    def __init__(self,headers=[],data=[], renderers=[]):
        self.headers = headers
        self.data = data
        self.renderers = renderers
        
        if len(data)>0:
            tmp_len = len(data[0])
        else:
            tmp_len = 0
        
        tmp_len = max(tmp_len, len(headers))
        for i in range(len(self.renderers),tmp_len):
            self.renderers.append(None)
    
    def __unicode__(self):
        s=u"<table>\n"
        tmp_headers=u"\t<thead>\n"
        for item in self.headers:
            tmp_headers+=u"\t\t<th>"+unicode(item)+u"</th>\n"
        if len(tmp_headers)>9:
            tmp_headers+=u"\t</thead>\n"
            s+=tmp_headers
        for row in self.data:
            tmp_row=u"\t<tr>\n"
            i=0
            for item in row:
                if self.renderers[i]!=None:
                    tmp_row+=u"\t\t<td>"+unicode(self.renderers[i](item))+u"</td>\n"
                else:
                    tmp_row+=u"\t\t<td>"+unicode(item)+u"</td>\n"
                i+=1
            tmp_row+=u"\t</tr>\n"
            s+=tmp_row
        s+=u"</table>"
        return mark_safe(s)

    def __str__(self):
        return self.__unicode__()
    
    def add_row(self,row):
        self.data.append(row)
    
    def add_field_renderer(self,column_number,renderer):
        self.renderers[column_number]=renderer
    
